package com.dlust.myplayer

import android.media.MediaPlayer
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.widget.FrameLayout
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.viewinterop.AndroidView
import android.util.Log

@Composable
fun MediaPlayerScreen(
  videoUrl: String = MediaConfig.CURRENT_VIDEO_URL,
  modifier: Modifier = Modifier
) {
  var mediaPlayer by remember { mutableStateOf<MediaPlayer?>(null) }
  var isPlaying by remember { mutableStateOf(false) }
  var isLoading by remember { mutableStateOf(true) }
  var currentUrl by remember { mutableStateOf(videoUrl) }
  var surfaceHolder by remember { mutableStateOf<SurfaceHolder?>(null) }
  
  // 监听URL变化，切换视频源
  LaunchedEffect(MediaConfig.currentVideoUrl.value) {
    val newUrl = MediaConfig.currentVideoUrl.value
    if (currentUrl != newUrl) {
      Log.d("MediaPlayerScreen", "URL变化: $currentUrl -> $newUrl")
      
      // URL已变化，需要重置播放器
      mediaPlayer?.apply {
        if (isPlaying) {
          stop()
        }
        reset()
        setDataSource(newUrl)
        setOnPreparedListener {
          isLoading = false
          start()
          isPlaying = true
        }
        setOnErrorListener { mp, what, extra ->
          Log.e("MediaPlayerScreen", "播放错误: what=$what, extra=$extra")
          isLoading = false
          false
        }
        prepareAsync()
        isLoading = true
      }
      currentUrl = newUrl
    }
  }

  // 初始化和清理播放器
  DisposableEffect(Unit) {
    Log.d("MediaPlayerScreen", "初始化MediaPlayer: $currentUrl")
    
    mediaPlayer = MediaPlayer().apply {
      setDataSource(currentUrl)
      setOnPreparedListener {
        isLoading = false
        start()
        isPlaying = true
        
        // 如果已经有SurfaceHolder，设置显示
        surfaceHolder?.let { holder ->
          setDisplay(holder)
        }
      }
      setOnErrorListener { mp, what, extra ->
        Log.e("MediaPlayerScreen", "播放错误: what=$what, extra=$extra")
        isLoading = false
        false
      }
      prepareAsync()
    }

    onDispose {
      Log.d("MediaPlayerScreen", "释放MediaPlayer资源")
      mediaPlayer?.apply {
        if (isPlaying) {
          stop()
        }
        release()
      }
      mediaPlayer = null
      surfaceHolder = null
    }
  }

  Box(modifier = modifier) {
    // 视频渲染视图
    AndroidView(
      factory = { ctx ->
        FrameLayout(ctx).apply {
          setBackgroundColor(android.graphics.Color.BLACK) // 设置黑色背景
          addView(SurfaceView(ctx).apply {
            holder.addCallback(object : SurfaceHolder.Callback {
              override fun surfaceCreated(holder: SurfaceHolder) {
                Log.d("MediaPlayerScreen", "Surface创建")
                surfaceHolder = holder
                mediaPlayer?.setDisplay(holder)
              }
              override fun surfaceChanged(p0: SurfaceHolder, p1: Int, p2: Int, p3: Int) {
                Log.d("MediaPlayerScreen", "Surface改变: p1=$p1, p2=$p2, p3=$p3")
              }
              override fun surfaceDestroyed(p0: SurfaceHolder) {
                Log.d("MediaPlayerScreen", "Surface销毁")
                surfaceHolder = null
              }
            })
          })
        }
      },
      modifier = Modifier.fillMaxSize()
    )

    // 加载指示器
    if (isLoading) {
      CircularProgressIndicator(modifier = Modifier.align(Alignment.Center))
    }

    // 播放控制按钮
    IconButton(
      onClick = {
        mediaPlayer?.let {
          if (isPlaying) {
            it.pause()
          } else {
            it.start()
          }
          isPlaying = !isPlaying
        }
      },
      modifier = Modifier.align(Alignment.BottomCenter)
    ) {
      Icon(
        painter = painterResource(
          id = if (isPlaying) R.drawable.ic_pause else R.drawable.ic_play
        ),
        contentDescription = null,
        tint = Color.White
      )
    }
  }
}